
#include "AdViewControl.h"
#include "AdserverRequest.h"
#include <QBitmap>
#include <QMessageBox>
#include <QNetworkReply>
#include <QDesktopServices>
#include "BrowserViewDlg.h"
#include <QNetworkConfiguration>
#include <QTimer>



AdViewControl::AdViewControl(QWidget *parent) :
    QWebView(parent)
{

            qWarning("Start Log");

            m_pImageArray = NULL;
            m_bGenerateRawImageEvent = FALSE;

            m_request = new AdserverRequest();
            m_bNavigate = FALSE;
            m_bFirstLaunch = TRUE;


            m_viewId = 1;
            m_Browser = FALSE;
            m_internalBrowser = true;
            m_reloadPeriod = AD_RELOAD_PERIOD;
            m_mode = MODE_ADS_ONLY;
            set_AdsType( ADS_TYPE_TEXT_AND_IMAGES );
            set_Over18( OVER_18_TYPE_UNDEFINED );
            set_Premium( PREMIUM_STATUS_BOTH );
            set_OutputFormat( OUTPUT_FORMAT_NORMAL );
            set_Count( 1 );
            m_testModeEnabled = FALSE;
            m_pixelModeEnabled = FALSE;
            m_textBorderEnabled = FALSE;
            m_bShowRichMedia = TRUE;

            m_horzAlign = HORZ_NONE;
            m_vertAlign = VERT_NONE;

            m_bFirstRun = TRUE;

            m_bRestart = FALSE;

            m_expanded = FALSE;


           // m_visible = FALSE;
            m_visible = true;


            connect( this, SIGNAL(linkClicked( const QUrl & )), this, SLOT(onLinkClicked( const QUrl & )) );
            this->page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks );
            updateTimer = new QTimer(this);


}

void AdViewControl::onLinkClicked( const QUrl & url)
{
    if (!m_internalBrowser)
    {
        QDesktopServices::openUrl(url);
    }
    else{
        BrowserViewDlg* browserViewDlg = new BrowserViewDlg(url);

        browserViewDlg->setWindowState(browserViewDlg->windowState() | Qt::WindowFullScreen);
        browserViewDlg->exec();
        emit AdWebViewClosing(url.toString());
        delete browserViewDlg;
    }
}

void AdViewControl::TimerTimeOut(){
    qWarning("Timer signal");
    Start();
}


void AdViewControl::Update()
{
    qWarning("Start update");

    Start();


    if(m_reloadPeriod > 0 ){
        qWarning(QString("Start update %1").arg(m_reloadPeriod).toAscii());
        updateTimer->stop();
        updateTimer->start(m_reloadPeriod);

        connect(updateTimer, SIGNAL(timeout()), this, SLOT(TimerTimeOut()));
    }
}

void AdViewControl::Start()
{
        ContentThread();
}



void AdViewControl::ContentThread()
{

        emit AdDownloadBegin();

        bodyBegin = "<body style=\"margin: 0px; padding: 0px; -webkit-user-select: none; -moz-user-select: none; -khtml-user-select: none; user-select: none; ";
        bodyEnd = "</body>";
        if (!this->m_strBackgroundColor.isEmpty())
                bodyBegin += "background-color: " + this->m_strBackgroundColor + ";";

        bodyBegin += "\">";

        if ( (this->m_horzAlign != AdViewControl::HORZ_NONE)
                || (this->m_vertAlign != AdViewControl::VERT_NONE) )
        {
                bodyBegin += "<table height=\"100%\" width=\"100%\"><tr><td style=\"";

                if (this->m_horzAlign != AdViewControl::HORZ_NONE){
                        bodyBegin += "text-align:";

                        switch(this->m_horzAlign)
                        {
                        case AdViewControl::HORZ_CENTER:
                                bodyBegin += "center;";
                                break;
                        case AdViewControl::HORZ_LEFT:
                                bodyBegin += "left;";
                                break;
                        case AdViewControl::HORZ_RIGHT:
                                bodyBegin += "right;";
                                break;
                        }
                }

                if (this->m_vertAlign != AdViewControl::VERT_NONE){
                        bodyBegin += "vertical-align:";

                        switch(this->m_vertAlign)
                        {
                        case AdViewControl::VERT_CENTER:
                                bodyBegin += "middle;";
                                break;
                        case AdViewControl::VERT_TOP:
                                bodyBegin += "top;";
                                break;
                        case AdViewControl::VERT_BOTTOM:
                                bodyBegin += "bottom;";
                                break;
                        }
                }
                bodyBegin += "\">";

                bodyEnd = "</td></tr></table>" + bodyEnd;
        }


                if (m_visible){
                    DownloadBannerSource();
                }
}

void AdViewControl::httpReadyRead()
{
    if (file) file->write(reply->readAll());
}

void AdViewControl::httpFinished()
{
    emit AdDownloadEnd();
    qWarning("Reply finished");

    QString dataBanner;

    if (reply->error() != QNetworkReply::NoError) {
        QString bodyB = "", bodyE = "";
        bodyB += "<table height=\"100%\" width=\"100%\"><tr><td style=\"";
        bodyB += "text-align:";
        bodyB += "center;";
        bodyB += "vertical-align:";
        bodyB += "middle;color:red;font-size:20pt;font-weight:bold;";
        bodyB += "\">";
        bodyE = "</td></tr></table>";
        dataBanner = "<H>Network Reply Error</H>";
        dataBanner = bodyB + dataBanner + bodyE;

        this->m_dataCurrent = dataBanner;
        emit AdDownloadError("Network Reply Error");
    }
    else{


        QString str = QString(reply->readAll());

        if (str == "invalid params" )
        {

            QString bodyB = "", bodyE = "";
            bodyB += "<table height=\"100%\" width=\"100%\"><tr><td style=\"";
            bodyB += "text-align:";
            bodyB += "center;";
            bodyB += "vertical-align:";
            bodyB += "middle;color:red;font-size:20pt;font-weight:bold;";
            bodyB += "\">";
            bodyE = "</td></tr></table>";
            dataBanner = "<H>Invalid parameters</H>";
            dataBanner = bodyB + dataBanner + bodyE;

            this->m_dataCurrent = dataBanner;
        }
        else if (!str.isEmpty()){
            this->m_dataCurrent = this->PostProcessData( bodyBegin + this->ReplaceImages( str ) + bodyEnd );
        }
    }
    this->setHtml(this->m_dataCurrent);
}




void AdViewControl::DownloadBannerSource()
{
        qWarning("DownloadBannerSource");


        QString url = m_expanded ? m_expandedUrl : m_request->CreateURL();
        qWarning(url.toAscii());


        QNetworkRequest networkRequest;

        networkRequest.setUrl(QUrl(url));

        if (get_UserAgent().length() > 0)
        networkRequest.setRawHeader("User-Agent", get_UserAgent().toAscii());


        QNetworkAccessManager *manager = new QNetworkAccessManager(0);
    /*    QNetworkConfiguration networkConfiguration  = manager->configuration();*/
        qWarning("Create reply");


        reply = manager->get( networkRequest );



        qWarning("Connect reply");


        connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));

}


/// <summary>
/// Required.
/// View id (default 1)
/// </summary>
int AdViewControl::get_ViewId()
{
        return m_viewId;
}

void AdViewControl::set_ViewId(int val)
{
        m_viewId = val;
}

/// <summary>
/// The flag which operates advertising opening. False - Ad opens in an external browser.
/// True - Ad opening at internal form.
/// (default = false)
/// </summary>

bool AdViewControl::get_InternalBrowser()
{
        return m_internalBrowser;
}

void AdViewControl::set_InternalBrowser(bool val)
{
        m_internalBrowser = val;
}


/// <summary>
/// Image which will be shown during advertising loading if there is no advertising in a cache.
/// (default = none)
/// </summary>
QBitmap AdViewControl::get_DefaultImage()
{
        return m_defaultImage;
}

void AdViewControl::set_DefaultImage(QBitmap val)
{
        m_defaultImage = val;
}


/// <summary>
/// The period of an automatic reload of advertising (in milliseconds).
/// (default = 120000)
/// </summary>
int AdViewControl::get_ReloadPeriod()
{
        return m_reloadPeriod;
}

void AdViewControl::set_ReloadPeriod(int val)
{
        m_reloadPeriod = val;
}

/// <summary>
/// The period of an automatic reload of advertising (in milliseconds).
/// (default = 120000)
/// </summary>
int AdViewControl::get_UpdateTime()
{
        return m_reloadPeriod / 1000;
}

void AdViewControl::set_UpdateTime(int val)
{
        if (val >= 0)
        {
                m_reloadPeriod = val * 1000;
        }
        else
        {
            return;
        }

}


/// <summary>
/// Required.
/// The id of the application.
/// </summary>
QString AdViewControl::get_AppId()
{
        return m_appId;
}
void AdViewControl::set_AppId( QString val)
{
        m_appId = val;
}

/// <summary>
/// Campaign name
/// </summary>
QString AdViewControl::get_Campaign()
{
        return m_campaign;
}
void AdViewControl::set_Campaign(QString val)
{
        m_campaign = val;
}

/// <summary>
/// Required.
/// Mode of viewer of advertising (use 1 - counter only, 2 - ads only, 3 - counter and ads)
/// (default = 2)
/// </summary>
int AdViewControl::get_Mode()
{
        return (int)m_mode;
}
void AdViewControl::set_Mode( int val)
{
        m_mode = (ADS_MODE)val;
}

/// <summary>
/// The id of the publisher site.
/// </summary>
QString AdViewControl::get_SiteId()
{
        return m_request->getSite();
}
void AdViewControl::set_SiteId(QString val)
{
        m_request->setSite(val);
}

/// <summary>
/// The id of the zone of publisher site.
/// </summary>
QString AdViewControl::get_ZoneId()
{
        return m_request->getZone();
}
void AdViewControl::set_ZoneId(QString val)
{
        m_request->setZone(val);
}

/// <summary>
/// The id of the publisher site.
/// </summary>
QString AdViewControl::get_Site()
{
        return m_request->getSite();
}
void AdViewControl::set_Site(QString val)
{
        if (val.toInt() > 0)
                m_request->setSite(val);
        else
                qFatal("Site valid values are >0");
                return;

}

/// <summary>
/// The id of the zone of publisher site.
/// </summary>
QString AdViewControl::get_Zone()
{
        return m_request->getZone();
}
void AdViewControl::set_Zone(QString val)
{
        if (val.toInt() > 0)
                m_request->setZone(val);
        else
        {
            qFatal("Zone valid values are >0");
            return;
        }
}

/// <summary>
/// The IP address of the carrier gateway over which the device is connecting.
/// Autodetected if not set.
/// </summary>
QString AdViewControl::get_Ip()
{
        return "";//m_request->getIp();
}
void AdViewControl::set_Ip( QString val )
{
        m_request->setIp(val);
}

/// <summary>
/// Keywords to search ad delimited by commas.
/// </summary>
QString AdViewControl::get_Keywords()
{
        return m_request->getKeywords();
}
void AdViewControl::set_Keywords(QString val)
{
        m_request->setKeywords(val);
}

/// <summary>
/// Required.
/// Type of advertisement (0 - disabled, 1 - text only, 2 - image only, 3 - image and text, 4 - SMS ad). SMS will be returned in XML.
/// (default = 3)
/// </summary>
int AdViewControl::get_AdsType()
{
        return m_request->getAdstype();
}
void AdViewControl::set_AdsType( int val )
{
        if ((val >= 1 && val <=3) || val == 6)
                m_request->setAdstype(val);
        else
        {
            qWarning("AdsType valid values are 1,2,3,6");
            return;
        }
}

/// <summary>
/// Filter by ad over 18 content (0 - disabled, 1 - deny over 18 content , 2 - only over 18 content, 3 - allow all ads including over 18 content).
/// (default = 0)
/// </summary>
int AdViewControl::get_Over18()
{
        return m_request->getOver18();
}
void AdViewControl::set_Over18(int val )
{
        m_request->setOver18(val);
}

/// <summary>
/// Latitude.
/// Autodetected if not set.
/// </summary>
QString AdViewControl::get_Latitude()
{
        return (QString)m_request->getLatitude();
}
void AdViewControl::set_Latitude( QString val )
{
        m_request->setLatitude(val);
}

/// <summary>
/// Longitude.
/// Autodetected if not set.
/// </summary>
QString AdViewControl::get_Longitude()
{
        return (QString)m_request->getLongitude();
}
void AdViewControl::set_Longitude(QString val)
{
        m_request->setLongitude(val);
}

/// <summary>
/// The browser user agent of the device making the request.
/// </summary>
QString AdViewControl::get_UserAgent()
{
        return m_request->getUa();
}
void AdViewControl::set_UserAgent(QString val)
{
        m_request->setUa(val);
}

/// <summary>
/// Filter by premium (0 - disabled, 1 - non-premium, 2 - premium only, 3 - both). Can be used only by premium publishers.
/// (default = 0)
/// </summary>
int AdViewControl::get_Premium()
{
        return m_request->getPremium();
}
void AdViewControl::set_Premium(int val)
{
        if (val >=0 && val <= 2)
                m_request->setPremium(val);
        else
                return;//WriteLog(ltError, _T("Premium valid values are 0,1,2,3") );
}

/// <summary>
/// Output format. Undefined = 0. Normal format uses key = 1. Parameter key should be set to 2 in order to use XML output and to 3 in order to use JSON output.
/// (default = 0)
/// </summary>
int AdViewControl::get_OutputFormat()
{
        return m_request->getKey();
}
void AdViewControl::set_OutputFormat(int val)
{
        m_request->setKey(val);
}

/// <summary>
/// Setting is test mode where, if the ad code is true, the ad response is "Test MODE".
/// (default = false)
/// </summary>
bool AdViewControl::get_TestModeEnabled()
{
        return m_testModeEnabled;
}
void AdViewControl::set_TestModeEnabled(bool val)
{
        m_testModeEnabled = val;
        m_request->setTestModeEnabled(m_testModeEnabled);
}

/// <summary>
/// Setting is test mode where, if the ad code is true, the ad response is "Test MODE".
/// (default = false)
/// </summary>
bool AdViewControl::get_Test()
{
        return m_testModeEnabled;
}
void AdViewControl::set_Test(bool val)
{
        m_testModeEnabled = val;
        m_request->setTestModeEnabled(m_testModeEnabled);
}

/// <summary>
/// Quantity of ads, returned by a server. Maximum value is 5.
/// (default = 1)
/// </summary>
int AdViewControl::get_Count()
{
        return m_request->getCount();
}
void AdViewControl::set_Count(int val)
{
        m_request->setCount(val);
}

/// <summary>
/// Country of visitor (for example: US).
/// Autodetected if not set.
/// </summary>
QString AdViewControl::get_Country()
{
        return "";//m_request->getCountry();
}
void AdViewControl::set_Country(QString val)
{
        m_request->setCountry(val);
}

QString AdViewControl::get_City()
{
        return m_request->getCity();
}

void AdViewControl::set_City( QString val)
{
        m_request->setCity(val);
}

QString AdViewControl::get_Area()
{
        return m_request->getArea();
}

void AdViewControl::set_Area( QString val)
{
        m_request->setArea(val);
}

QString AdViewControl::get_Metro()
{
        return m_request->getMetro();
}

void AdViewControl::set_Metro( QString val)
{
        m_request->setMetro(val);
}

QString AdViewControl::get_ZIP()
{
        return m_request->getZIP();
}

void AdViewControl::set_ZIP( QString val)
{
        m_request->setZIP(val);
}



/// <summary>
/// Region of visitor (for example: NY).
/// </summary>
QString AdViewControl::get_Region()
{
        return m_request->getRegion();
}
void AdViewControl::set_Region( QString val)
{
        m_request->setRegion(val);
}

/// <summary>
/// Show borders around text ads (false - non-borders, true - show borders).
/// (default = false)
/// </summary>
bool AdViewControl::get_TextBorderEnabled()
{
        return m_textBorderEnabled;
}

void AdViewControl::set_TextBorderEnabled(bool val)
{
        m_textBorderEnabled = val;
        m_request->setTextborderEnabled(m_textBorderEnabled);
}

/// <summary>
/// Borders color
/// </summary>
QString AdViewControl::get_BorderColor()
{
        return m_request->getParamBorder();
}
void AdViewControl::set_BorderColor(QString val)
{
        m_request->setParamBorder(val);
}

/// <summary>
/// Background color in borders
/// </summary>
QString AdViewControl::get_BackgroundColor()
{
        return m_request->getParamBG();
}
void AdViewControl::set_BackgroundColor(QString val)
{
        m_strBackgroundColor = val;
        m_request->setParamBG(val);
}

/// <summary>
/// Text color
/// </summary>
QString AdViewControl::get_TextColor()
{
        return m_request->getParamLINK();
}
void AdViewControl::set_TextColor(QString val)
{
        m_request->setParamLINK(val);
}

/// <summary>
/// Carrier name.
/// Autodetected if not set.
/// </summary>
QString AdViewControl::get_Carrier()
{
        return m_request->getCarrier();
}
void AdViewControl::set_Carrier( QString val )
{
        m_request->setCarrier(val);
}

int AdViewControl::get_ImageMinWidth()
{
        return m_request->get_min_size_x();
}

void AdViewControl::set_ImageMinWidth(int val)
{
        m_request->set_min_size_x(val);
}

int AdViewControl::get_ImageMinHeight()
{
        return m_request->get_min_size_y();
}

void AdViewControl::set_ImageMinHeight(int val)
{
        m_request->set_min_size_y(val);
}

int AdViewControl::get_ImageMaxWidth()
{
        return m_request->get_size_x();
}

void AdViewControl::set_ImageMaxWidth(int val)
{
        m_request->set_size_x(val);
}

int AdViewControl::get_ImageMaxHeight()
{
        return m_request->get_size_y();
}

void AdViewControl::set_ImageMaxHeight(int val)
{
        m_request->set_size_y(val);
}

int AdViewControl::get_MinSizeX()
{
        return m_request->get_min_size_x();
}

void AdViewControl::set_MinSizeX(int val)
{
        if (val > 0)
                m_request->set_min_size_x(val);
        else
                return;//WriteLog(ltError, _T("MinSizeX valid values >0") );
}

int AdViewControl::get_MinSizeY()
{
        return m_request->get_min_size_y();
}

void AdViewControl::set_MinSizeY(int val)
{
        if (val > 0)
                m_request->set_min_size_y(val);
        else
                return;//WriteLog(ltError, _T("MinSizeY valid values >0") );
}

int AdViewControl::get_MaxSizeX()
{
        return m_request->get_size_x();
}

void AdViewControl::set_MaxSizeX(int val)
{
        if (val > 0)
                m_request->set_size_x(val);
        else
                return;//WriteLog(ltError, _T("MaxSizeX valid values >0") );
}

int AdViewControl::get_MaxSizeY()
{
        return m_request->get_size_y();
}

void AdViewControl::set_MaxSizeY(int val)
{
        if (val > 0)
                m_request->set_size_y(val);
        else
                return;//WriteLog(ltError, _T("MaxSizeY valid values >0") );
}



/// <summary>
/// URL of site for which it is necessary to receive advertising.
/// </summary>
/*
QString AdViewControl::get_Site()
{
        return m_request->getUrl();
}
void AdViewControl::set_Site(QString val)
{
        m_request->setUrl( val );
}
*/

/// <summary>
/// If true, return redirect to image for ad (or tracking pixel 1x1) directly (instead of html response).
/// (default = false)
/// </summary>
bool AdViewControl::get_PixelModeEnabled()
{
        return m_pixelModeEnabled;
}
void AdViewControl::set_PixelModeEnabled(bool val)
{
        m_pixelModeEnabled = val;
        m_request->setPixelModeEnabled(m_pixelModeEnabled);
}

QString AdViewControl::get_AdServerUrl()
{
        return m_request->getAdserverURL();
}
void AdViewControl::set_AdServerUrl(QString val)
{
        m_request->setAdserverURL( val );
}

QString AdViewControl::get_AdvertiserId()
{
        return m_advertiserId;
}
void AdViewControl::set_AdvertiserId(QString val)
{
        if (val.toInt() > 0)
                m_advertiserId = val;
        else
                return;//WriteLog(ltError, _T("AdvertiserId valid values >0") );
}

QString AdViewControl::get_GroupCode()
{
        return m_groupCode;
}
void AdViewControl::set_GroupCode(QString val)
{
        m_groupCode = val;
}

AdViewControl::HORIZONTAL_ALIGNMENT AdViewControl::get_HorizontalAlignment()
{
        return m_horzAlign;
}

void AdViewControl::set_HorizontalAlignment(HORIZONTAL_ALIGNMENT val)
{
        m_horzAlign = val;
}

AdViewControl::VERTICAL_ALIGNMENT AdViewControl::get_VerticalAlignment()
{
        return m_vertAlign;
}

void AdViewControl::set_VerticalAlignment(VERTICAL_ALIGNMENT val)
{
        m_vertAlign = val;
}

bool AdViewControl::get_DisplayRichMediaType()
{
        return m_bShowRichMedia;
}

void AdViewControl::set_DisplayRichMediaType(bool bVal)
{
        m_bShowRichMedia = bVal;
}

QString AdViewControl::get_CustomParameters()
{
        QString res;
        for (int f = 0; f < m_request->custom_parameters.count(); f++)
        {
                res += m_request->custom_parameters.keys().value( f );
                res += ",";
                res += m_request->custom_parameters.values().value( f );
                if (f != m_request->custom_parameters.count()-1) res += ",";
        }

        return res;
}

void AdViewControl::set_CustomParameters(QString val)
{
        QStringList paramPairs = val.split(",");

        SetCustomParametersArray(paramPairs);
}

void AdViewControl::SetCustomParametersArray(QStringList paramPairs)
{
        for (int f = 0; f < paramPairs.count(); f+= 2)
        {
                m_request->custom_parameters.insert(paramPairs.value(f), paramPairs.value(f+1));
        }
}

void AdViewControl::SetCustomParameter( QString strName, QString strValue )
{
        if (m_request->custom_parameters.contains(strName)){
                m_request->custom_parameters.remove(strName);
        }
        m_request->custom_parameters.insert(strName, strValue );
}

bool AdViewControl::RemoveCustomParameter( QString strName )
{
        if (m_request->custom_parameters.contains(strName)){
                m_request->custom_parameters.remove(strName);
                return true;
        }
        return false;
}


QString AdViewControl::GetCustomParameter( QString strName )
{
        if (m_request->custom_parameters.contains(strName))
        { return m_request->custom_parameters.value( strName );
        }

        return "";
}

bool AdViewControl::get_GenerateRawImageEvent()
{
        return m_bGenerateRawImageEvent;
}

void AdViewControl::set_GenerateRawImageEvent(bool bVal)
{
        m_bGenerateRawImageEvent = bVal;
}

QString AdViewControl::LoadOrmmaNamespace()
{
    return "";
}

QString AdViewControl::PostProcessData( QString data )
{
        return QString("<HEAD><script type=\"text/javascript\" language=\"javascript\">") + m_strOrmmaNamespace + QString("</script></HEAD>") + data;
}

QString AdViewControl::ReplaceImages( QString src )
{
        return src;
}

QString AdViewControl::GetCachePath()
{
    return "";
}
